package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RequestMapping("/dish")
@RestController
public class DishController {

    @Autowired
    private IDishService iDishService;

    @Autowired
    private ICategoryService iCategoryService;

    @Autowired
    private IDishFlavorService iDishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "dish",allEntries = true)
    // aop 切面只检查了这个方法，并且给 dishDto 赋默认值
    public R addDish(@RequestBody DishDto dishDto){
        // todo 之前那个表设置的主键唯一索引，相同就会报错



        iDishService.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        // todo
// Preparing: INSERT INTO dish_flavor ( id, dish_id, name, value, create_time, update_time, create_user, update_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )
//==> Parameters: 1535182336088342530(Long), 1535182240214941698(Long), 甜味(String), ["无糖","少糖","半糖","多糖","全糖"](String), null, null, null, null
        // 但是没有给 flavors 的 create_time 赋值，这时候数据库又必须要求为非空，所以报错
        iDishFlavorService.saveBatch(flavors);

        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);


        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){
        IPage<Dish> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        qw.orderByDesc(Dish::getUpdateTime);

        IPage<Dish> page2 = iDishService.page(page1, qw);
        List<Dish> records = page2.getRecords();
        long total = page2.getTotal();

        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : records) {
            Long id = record.getCategoryId();
            Category category = iCategoryService.getById(id);
            String name1 = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(name1);
            BeanUtils.copyProperties(record,dishDto);
            dishDtos.add(dishDto);

        }

        Map data = new HashMap();

        data.put("records",dishDtos);
        data.put("total",total);

        return R.success(data);
    }

    @GetMapping("/{id}")
    public R select(@PathVariable Long id){

        LambdaQueryWrapper<Dish> l = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Dish> eq = l.eq(Dish::getId, id);
        LambdaQueryWrapper<DishFlavor> ll = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<DishFlavor> eq1 = ll.eq(DishFlavor::getDishId, id);
        Long one = iDishService.getOne(l).getCategoryId();
        LambdaQueryWrapper<Category> lll = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> eq2 = lll.eq(Category::getId, one);

        Dish one2 = iDishService.getOne(l);
        //DishFlavor one1 = iDishFlavorService.getOne(ll);
        //String name = iCategoryService.getOne(lll).getName();
        List<DishFlavor> list = iDishFlavorService.list(ll);

        DishDto dishDto = new DishDto();
        //dishDto.setCategoryName(name);
        BeanUtils.copyProperties(one2,dishDto);
        dishDto.setFlavors(list);



        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R updateOne(@RequestBody DishDto dishDto){






        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,id);
        iDishFlavorService.remove(qw);
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());

        }
        // todo
// Preparing: INSERT INTO dish_flavor ( id, dish_id, name, value, create_time, update_time, create_user, update_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )
//==> Parameters: 1535182336088342530(Long), 1535182240214941698(Long), 甜味(String), ["无糖","少糖","半糖","多糖","全糖"](String), null, null, null, null
        // 但是没有给 flavors 的 create_time 赋值，这时候数据库又必须要求为非空，所以报错
        iDishFlavorService.saveBatch(flavors);

        iDishService.updateById(dishDto);
        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R deleteByIds(@RequestParam List<Long> ids){

        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.in(DishFlavor::getDishId,ids);
        iDishFlavorService.remove(qw);
        iDishService.removeByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){


        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus,status);
        qw.in(Dish::getId,ids);
        iDishService.update(qw);

        for (Long id : ids) {

            Dish dish = new Dish();

            dish.setId(id);
            dish.setStatus(status);
            iDishService.updateById(dish);
        }

        return R.success("success");
    }

    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#dish.categoryId")
    public R selecetList(Dish dish ){

  /*      List<DishDto> dishDtos;
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtos= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null){
            return R.success(dishDtos);
        }
*/
        List<DishDto>dishDtos = new ArrayList<>();
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        qw.eq(Dish::getStatus,1);
        qw.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = iDishService.list(qw);
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            LambdaUpdateWrapper<DishFlavor> q = new LambdaUpdateWrapper<>();
            q.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> list1 = iDishFlavorService.list(q);
            dishDto.setFlavors(list1);
            dishDtos.add(dishDto);
        }

        //redisTemplate.opsForValue().set(key,dishDtos);

        return R.success(dishDtos);
    }

}
